// 提交链接 https://leetcode.cn/problems/house-robber-iii/submissions/569576486/
// 337. 打家劫舍 III
// 完成日期： 2024.10.7
// 树状dp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int rob(TreeNode* root) {
        pair<int, int> ans = dfs(root);
        return max(ans.first, ans.second);
    }
    pair<int, int> dfs(TreeNode* root)
    {
        int ans1 = root->val, ans2 = 0;
        if (root->left)
        {
            pair<int, int> temp = dfs(root->left);
            ans1 += temp.second;
            ans2 += max(temp.first, temp.second);
        }
        if (root->right)
        {
            pair<int, int> temp = dfs(root->right);
            ans1 += temp.second;
            ans2 += max(temp.first, temp.second);
        }
        return pair<int, int>(ans1, ans2);
    }
};